package top.codetheory.thread._001_打断;

import lombok.extern.slf4j.Slf4j;

/**
 * @author: CodeTheory
 * @since: 2024/4/21 下午6:14
 **/
@Slf4j
public class _005_线程状态 {

    /**
     *<img src="https://gitee.com/codetheory/img-on1/raw/master/img01/1713695282423-2024-4-2118:28:02.png"  />
     */
    public static void main(String[] args) {

        Object lock = new Object();

        // new 初始状态, 没有调用start方法
        Thread t1 = new Thread(() -> {
        }, "t1");

        // runnable 运行状态 线程在运行中
        Thread t2 = new Thread(() -> {
            while (true) {

            }
        }, "t2");
        t2.start();

        // terminated 终止状态 线程执行完毕
        Thread t3 = new Thread(() -> {

        }, "t3");
        t3.start();

        // timed_waiting 时间等待状态 线程在等待中
        Thread t4 = new Thread(() -> {
            // 加锁是为了测试 t6 的blocked状态
            synchronized (lock) {
                try {
                    Thread.sleep(1000000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

        }, "t4");
        t4.start();

        // waiting 等待状态 线程在等待中 等待 t2 线程执行完毕
        Thread t5 = new Thread(() -> {
            try {
                t2.join();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "t5");
        t5.start();

        // 睡眠一会, 目的: 让 t4 线程先执行, 先获得锁, 然后t6执行的时候, 就获取不到锁, 所以t6是blocked状态
        // 如果不加这个代码, 那么t4和t6的状态就不确定, 但是必定一个是 timed_waiting 时间等待状态, 一个是 blocked 阻塞状态
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        // blocked 阻塞状态 线程在等待锁 因为t4线程先运行, t6获取不到锁, 所以是blocked 阻塞状态
        Thread t6 = new Thread(() -> {
            synchronized (lock) {
                try {
                    Thread.sleep(1000000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

        }, "t6");
        t6.start();



        log.info("t1状态: {}", t1.getState());
        log.info("t2状态: {}", t2.getState());
        log.info("t3状态: {}", t3.getState());
        log.info("t4状态: {}", t4.getState());
        log.info("t5状态: {}", t5.getState());
        log.info("t6状态: {}", t6.getState());
    }
}